
#
# Session support
#  
class Session < ActiveRecord::Base

    def update
      super
    end

    ##########################################################################
    # slightly modified hash; from camping - probably obsolete now
    ##########################################################################

    #
    # hash with indifferent access from ruby; with some local changes
    # 
    H = HashWithIndifferentAccess
    class H
      def method_missing(m,*a)
        if m.to_s =~ /=$/
          self[$`] = a[0]
        elsif a.empty?
          self[m]
        else
          raise NoMethodError, "#{m}"
        end
      end
      alias_method :u, :regular_update
    end


      serialize :ivars
      def []=(k, v) # :nodoc:
          self.ivars[k] = v
      end
      def [](k) # :nodoc: note the rescue nil handles if ivars is undefined
          self.ivars[k] rescue nil
      end
  
      RAND_CHARS = [*'A'..'Z'] + [*'0'..'9'] + [*'a'..'z']
  
      # Generates a new session ID and creates new session in the database.
      def self.generate cookies
          rand_max = RAND_CHARS.size
          sid = (0...32).inject("") { |ret,_| ret << RAND_CHARS[rand(rand_max)] }
          sess = Session.create :hashid => sid, :ivars => H[]
          cookies['anselm_sid'] = sess.hashid
          sess
      end
  
      # Gets the existing session based on the sid available in cookies.
      # If none is found, generates a new session.
      def self.manufacture cookies
          if cookies['anselm_sid']
              session = Session.find_by_hashid cookies['anselm_sid']
          end
          unless session
              session = Session.generate cookies
          end
          session
      end
  
      def self.schema_drop
        return if !table_exists?
        ActiveRecord::Schema.define do
          drop_table :sessions
        end
      end
  
      # xxx not sure i want to say this here; perhaps as an external migration
      def self.schema_001
        return if table_exists?
        ActiveRecord::Schema.define do
          create_table :sessions, :force => true do |t|
            t.column :id,          :integer, :null => false
            t.column :hashid,      :string,  :limit => 32
            t.column :created_at,  :datetime
            t.column :ivars,       :text
          end
        end
      end
end

Session.schema_001
